package com.yinhe.music.yhmusic.manager;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.JsonArray;
import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.common.utils.JsonUtil;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.type.person.BaseInfo;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.constants.BasicConfig;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.MenuDBEntity;
import com.yinhe.music.yhmusic.db.bean.SongDBEntity;
import com.yinhe.music.yhmusic.downmusic.DownloadStatus;
import com.yinhe.music.yhmusic.http.StatusCode;
import com.yinhe.music.yhmusic.log.BlankUtil;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.network.response.Response;
import com.yinhe.music.yhmusic.network.response.ResponseTransformer;
import com.yinhe.music.yhmusic.service.PlayService;
import com.yinhe.music.yhmusic.utils.SongUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MusicManagerPresenter extends BasePresenter<BaseModel, IMusicManagerContract.IMusicManagerView>
        implements IMusicManagerContract.IMusicManagerPresenter {
    @Override
    public void reqDownMusic(List<Music> musicList, String quality, PlayService mService) {
        if (getView() == null) {
            return;
        }

        String downString = "";
        try {
            JsonArray jsonArray = new JsonArray();
            for (Music music : musicList) {
                jsonArray.add(music.getSongId());
            }
            downString = JsonUtil.ObjectToJson(jsonArray);
        } catch (Exception e) {
            LogUtils.e(e);
        }

        addSubscription(mModel.batchDownload(downString, quality)
                .compose(ResponseTransformer.handleResult())
                .compose(schedulerProvider.applySchedulers())
                .subscribe(baseInfo -> {
                            setDownMusicInfo(baseInfo, musicList, mService, quality);
                            getView().showToast("已加入下载列表");
                            RxBus.get().post(RxBusEventType.Music.GET_DOWN_URL, RxbusListObject.instance(musicList));
                        },
                        throwable -> {
                            getView().showMessage(throwable);
                        }));
    }

    private void setDownMusicInfo(BaseInfo baseInfo, List<Music> musicList, PlayService mService, String quality) {
        List<BaseInfo> urlList = baseInfo.getPlayUrlList();
        int index = 0;
        for (BaseInfo i : urlList) {
            Music music = musicList.get(index);
            if (!BlankUtil.isBlank(i.getPlayUrl()) && i.getSongId() == music.getSongId()) {
                music.setFilePath(BasicConfig.getInstance().getMusicDownLoadDir() +
                        File.separator + music.getFileName());
                music.url = i.getPlayUrl();
                if (quality == null) {
                    quality = IConstants.Common;
                }
                music.setQuality(quality);
                mService.addDownloadTask(music);
            }
            index++;
        }
    }

    @Override
    public void getBatchDownId(List<Music> mList) {
        List<Music> downList = new ArrayList<>();
        for (Music i : mList) {
            boolean isLocal = DataBaseAccessor.getInstance().isExistSongDBId((int) i.getSongId());
            boolean hasDown = DataBaseAccessor.getInstance().isExsitIdSyn(i.getId(), DownloadStatus.DOWNLOAD_STATUS_COMPLETED);
            if (i.isChecked() && !hasDown && !isLocal) {
                downList.add(i);
            }
        }
        if (downList.isEmpty()) {
            getView().showToast("请选择要下载的歌曲");
            return;
        }
        getView().showDownTips(downList);

    }

    @Override
    public void getDeleteList(List<Music> musicList) {
        List<Integer> deleteList = new ArrayList<>();
        for (Music music : musicList) {
            if (music.isChecked()) {
                deleteList.add((int) music.getSongId());
            }
        }

        if (!deleteList.isEmpty()) {
            getView().showDeleteDialog(deleteList);
        }
    }

    @Override
    public void deleteMusic(List<Integer> deleteList, List<Integer> hasDownList, int songMenuId, int mType, boolean deleteFile) {
        switch (mType) {
            case IConstants.DOWN_FINISH_MANAGER:
                DataBaseAccessor.getInstance().deleteDownMusicByList(hasDownList, deleteFile);
                break;
            case IConstants.RECENT_PLAY_MANAGER:
                DataBaseAccessor.getInstance().deleteRecentSongList(deleteList);
                break;
            default:
                if (deleteFile) {
                    DataBaseAccessor.getInstance().deleteDownMusicByList(hasDownList, deleteFile);
                }
                reqDeleteMenuMusic(deleteList, songMenuId);
                break;
        }
    }

    @Override
    public void reqDeleteMenuMusic(List<Integer> songIdList, int songMenuId) {
        if (getView() == null) {
            return;
        }

        getView().showLoading();

        List<Integer> onlineList = new ArrayList<>();
        for (int id : songIdList) {
            SongDBEntity songDBEntity = DataBaseAccessor.getInstance().getSongById(id);
            if (songDBEntity != null && songDBEntity.isSyn()) {
                SongUtil.removeSong((int) songDBEntity.getSongid(), songMenuId);
            } else {
                onlineList.add(id);
            }
        }

        if (!onlineList.isEmpty()) {
            addSubscription(mModel.deleteUserSongMenuSong(songMenuId, JsonUtil.getJsonArray(onlineList))
                    .compose(schedulerProvider.applySchedulers())
                    .subscribe(baseInfo -> {
                                handleDeleteResp(baseInfo, onlineList,songMenuId);
                            },
                            throwable -> {
                                getView().showMessage(throwable);
                            }));
        } else {
            getView().showToast("已删除");
            getView().hideLoading();
        }
    }

    private void handleDeleteResp(Response<BaseInfo> baseInfo, List<Integer> onlineList, int songMenuId) {
        if (baseInfo.getCode() == StatusCode.CHANGE_DATA) {
            MenuDBEntity menuDBEntity = DataBaseAccessor.getInstance().getMenuByIdSyn(songMenuId);
            if (menuDBEntity != null) {
                if (menuDBEntity.getSongnum() > 0) {
                    menuDBEntity.setSongnum(menuDBEntity.getSongnum() - 1);
                }
                DataBaseAccessor.getInstance().updateMenu(menuDBEntity);
            }
            RxBus.get().post(RxBusEventType.SongMenu.DELETE_MENU_MUSIC, RxbusListObject.instance(onlineList));
            getView().showToast(baseInfo.getMsg());
        } else {
            getView().showToast(baseInfo.getMsg());
        }
        getView().hideLoading();
    }

}
